﻿
using System;

using System.Runtime.InteropServices;
using System.IO;
using System.Collections.Generic;
using System.Text;



namespace DiskFreeSpaceEx
{

    class FreeSpace
    {

        //The Win32 API needed
        [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int WNetGetConnection([MarshalAs(UnmanagedType.LPTStr)] string localName, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName, ref int length);

        //MappedDrive class (will hold our results)
        public class MappedDrive
        {
            public string LocalDriveLetter { get; set; }
            public string UncPath { get; set; }
        }

        /// <summary>
        /// method for retrieving the UNC path for all mapped drives
        /// </summary>
        /// <returns>a generic list of MappedDrive</returns>
        public List<MappedDrive> GetPath()
        {
            List<MappedDrive> driveList = new List<MappedDrive>();

            //loop through all drives found in GetDrives
            foreach (DriveInfo drive in DriveInfo.GetDrives())
                //check the drive type, if Network then get it's information
                //and add to our list
                if (drive.DriveType.Equals(System.IO.DriveType.Network))
                {
                    //variable to hold the returned list
                    StringBuilder path = new StringBuilder(255);

                    //capacity of the string builder (required for the Win32 API call
                    int len = path.Capacity;

                    //call the Win32 API
                    WNetGetConnection(drive.Name.Replace("\\", ""), path, ref len);

                    //add each drive
                    driveList.Add(
                            new MappedDrive
                            {
                                LocalDriveLetter = drive.Name,
                                UncPath = path.ToString()
                            });
                    Console.WriteLine(path);
                }

            return driveList;
        }

    }

}


